<?php

namespace app\service\impl;

use app\enum\MessageConstant;
use app\popo\dto\ShoppingCartDTO;
use app\popo\model\ShoppingCart;
use app\repository\ShoppingCartRepository;
use app\service\ShoppingCartService;
use app\support\JwtHelper;
use DI\Attribute\Inject;
use support\exception\BusinessException;

class ShoppingCartServiceImpl implements ShoppingCartService
{
    #[Inject]
    protected ShoppingCartRepository $shoppingCartRepository;

    /**
     * 添加购物车
     * @param ShoppingCartDTO $shoppingCartDTO
     * @return void
     * @throws BusinessException
     */
    public function addShoppingCart(ShoppingCartDTO $shoppingCartDTO): void
    {
        // 获取当前登录用户ID (这里需要根据你的JWT实现调整)
        $userId = $this->getCurrentUserId();
        
        // 构建查询条件
        $conditions = [
            'user_id' => $userId,
            'dish_id' => $shoppingCartDTO->getDishId(),
            'setmeal_id' => $shoppingCartDTO->getSetmealId(),
            'dish_flavor' => $shoppingCartDTO->getDishFlavor(),
        ];

        // 查找是否已存在相同的购物车项
        $existingCart = $this->shoppingCartRepository->findByConditions($conditions);

        if ($existingCart) {
            // 如果存在，增加数量
            $newNumber = $existingCart->number + $shoppingCartDTO->getNumber();
            $this->shoppingCartRepository->updateNumber($existingCart, $newNumber);
        } else {
            // 如果不存在，创建新的购物车项
            $cartData = [
                'user_id' => $userId,
                'dish_id' => $shoppingCartDTO->getDishId(),
                'setmeal_id' => $shoppingCartDTO->getSetmealId(),
                'dish_flavor' => $shoppingCartDTO->getDishFlavor(),
                'number' => $shoppingCartDTO->getNumber(),
            ];

            // 根据商品类型设置名称、图片和金额
            if ($shoppingCartDTO->getDishId()) {
                $dish = $this->shoppingCartRepository->getDishById($shoppingCartDTO->getDishId());
                if ($dish) {
                    $cartData['name'] = $dish->name;
                    $cartData['image'] = $dish->image;
                    $cartData['amount'] = $dish->price;
                }
            } elseif ($shoppingCartDTO->getSetmealId()) {
                $setmeal = $this->shoppingCartRepository->getSetmealById($shoppingCartDTO->getSetmealId());
                if ($setmeal) {
                    $cartData['name'] = $setmeal->name;
                    $cartData['image'] = $setmeal->image;
                    $cartData['amount'] = $setmeal->price;
                }
            }

            $this->shoppingCartRepository->add($cartData);
        }
    }

    /**
     * 查看购物车
     * @return array
     */
    public function showShoppingCart(): array
    {
        $userId = $this->getCurrentUserId();
        return $this->shoppingCartRepository->getByUserId($userId);
    }

    /**
     * 清空购物车
     * @return void
     */
    public function cleanShoppingCart(): void
    {
        $userId = $this->getCurrentUserId();
        $this->shoppingCartRepository->cleanByUserId($userId);
    }

    /**
     * 删除购物车中一个商品
     * @param ShoppingCartDTO $shoppingCartDTO
     * @return void
     * @throws BusinessException
     */
    public function subShoppingCart(ShoppingCartDTO $shoppingCartDTO): void
    {
        $userId = $this->getCurrentUserId();
        
        // 构建查询条件
        $conditions = [
            'user_id' => $userId,
            'dish_id' => $shoppingCartDTO->getDishId(),
            'setmeal_id' => $shoppingCartDTO->getSetmealId(),
            'dish_flavor' => $shoppingCartDTO->getDishFlavor(),
        ];

        // 查找购物车项
        $existingCart = $this->shoppingCartRepository->findByConditions($conditions);

        if (!$existingCart) {
            throw new BusinessException("购物车中不存在该商品");
        }

        // 减少数量
        $newNumber = $existingCart->number - $shoppingCartDTO->getNumber();
        
        if ($newNumber <= 0) {
            // 如果数量小于等于0，删除该项
            $this->shoppingCartRepository->delete($existingCart);
        } else {
            // 否则更新数量
            $this->shoppingCartRepository->updateNumber($existingCart, $newNumber);
        }
    }

    /**
     * 获取当前用户ID
     * @return int
     * @throws BusinessException
     */
    private function getCurrentUserId(): int
    {
        return JwtHelper::getUser()->id;
    }
}